package com.uzhie.jt808.service;

import com.uzhie.jt808.JT808SessionManager;
import com.uzhie.jt808.JT808SysCache;
import com.uzhie.jt808.msg.JT808MsgBean;
import com.uzhie.jt808.util.JT808ProtocolUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Created by TangFei on 2018/7/30.
 */
public abstract class BaseService {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    @Qualifier(value = "sysCache")
    protected JT808SysCache sysCache;

    @Autowired
    @Qualifier(value = "sessionManager")
    protected JT808SessionManager sessionManager;

    @Autowired
    @Qualifier(value = "jt808ThreadExecutor")
    protected ThreadPoolTaskExecutor taskExecutor;

    /**
     * 通用应答消息体
     *
     * @param flowNumInt 消息流水号
     * @param msgIDInt   消息ID
     * @param result     结果
     * @return
     */
    protected byte[] commonRespBodyBytes(int flowNumInt, int msgIDInt, int result) {
        return JT808ProtocolUtil.commonRespBodyBytes(flowNumInt, msgIDInt, result);
    }

    /**
     * 构建808 协议bean
     *
     * @param msgID     消息ID
     * @param flowNum   流水号
     * @param simNum    sim 卡号
     * @param bodyBytes 消息体
     * @return
     */
    protected JT808MsgBean build808Obj(int msgID, int flowNum, String simNum, byte[] bodyBytes) {
        return JT808ProtocolUtil.build808Obj(msgID, flowNum, simNum, bodyBytes);
    }

    /**
     * 刷新session
     *
     * @param msgBean
     */
    protected void refreshSession(JT808MsgBean msgBean) {
        String channelID = msgBean.getChannelHandlerContext().channel().id().asShortText();
        sessionManager.refreshChannelSimMap(channelID, msgBean.getHeader().getSimNum());
        sessionManager.refreshSimSession(msgBean.getHeader().getSimNum(), msgBean.getChannelHandlerContext().channel());
        logger.debug("channelID:" + channelID + "绑定session sim卡号:" + msgBean.getHeader().getSimNum());
    }

}
